/**
 * CoffeeMilk (C) 2010 Amen Hamdan
 * 
 * See the NOTICE file distributed with this work for additional 
 * information regarding copyright ownership.  This file is licenses
 * to you under the Apache License, Version 2.0 (the "License"); you 
 * may not use this file except in compliance with the License.  You 
 * may obtain a copy of the License at
 * 
 *     http://www.apache.org/licenses/LICENSE-2.0
 *     
 * Unless required by applicable law or agreed to in writing, software 
 * distributed under the License is distributed on an "AS IS" BASIS, 
 * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or 
 * implied. See the License for the specific language governing 
 * permissions and limitations under the License.    
 * 
 */
package ameen.rtm.coffeemilk.ui.tablemodel;

import java.awt.event.ActionEvent;
import java.awt.event.ActionListener;
import java.beans.PropertyChangeEvent;
import java.beans.PropertyChangeListener;

import javax.swing.Timer;
import javax.swing.table.AbstractTableModel;

import ameen.rtm.lib.types.RtmTask;
import ameen.rtm.lib.types.TasksVector;

@SuppressWarnings("serial")
public class TasksTableModel extends AbstractTableModel implements PropertyChangeListener {
	private TasksVector tasksVector;
	
	public TasksTableModel(TasksVector tasks) {
		if(tasks == null) {
			tasksVector = new TasksVector();
		} else {
			tasksVector = tasks;
			for(RtmTask task : tasksVector) task.addPropertyChangeListener(this);
		}
		tasksVector.addPropertyChangeListener(this);
	}
	
	@Override
	public int getColumnCount() {
		return 6;
	}

	@Override
	public int getRowCount() {
		return tasksVector.size();
	}

	@Override
	public Object getValueAt(int rowIndex, int columnIndex) {
		RtmTask currentTask = tasksVector.get(rowIndex);
	
		switch (columnIndex) {
		case 0:
			return currentTask.getPriority();

		case 1:
			return currentTask.isCompleted();
			
		case 2:
			return " " + currentTask.getName();
			
		case 3:
			return currentTask.getDueDate();
		
		case 4:
			return "";
			
		default:
			return null;
		}
	}
	
	@Override
	public void propertyChange(final PropertyChangeEvent evt) {
		if(evt.getPropertyName().equals(TasksVector.ELEMENT_ADDED)) {
			RtmTask newTask = (RtmTask) evt.getNewValue();
			newTask.addPropertyChangeListener(this);
		}
		
		if(evt.getPropertyName().equals(RtmTask.COMPLETED)) {
			ActionListener timerAction = new ActionListener() {
				@Override
				public void actionPerformed(ActionEvent e) {
					// TODO Auto-generated method stub
					tasksVector.remove(evt.getSource());
					fireTableDataChanged();
				}
			};
			Timer timer = new Timer(500, timerAction);
			timer.setRepeats(false);
			timer.start();
		} 
		fireTableDataChanged();
	}
}
